// +build mysql

package mysql

import (
	"db/models"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/xorm"
)

type DB struct {
	*xorm.Engine
}

const (
	dbName="mysql"
)
//affected, err := engine.Table(new(User)).Id(id).Update(map[string]interface{}{"age":0})
//sql = "update `userinfo` set username=? where id=?"
//res, err := engine.Exec(sql, "xiaolun", 1)
func (db*DB) NewUser(user models.User,userInfos []models.UserInfo)(userID int64,err error) {
	sess:=db.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return -1,err
	}
	//描述的自增，在插入后，将自动填充自增字段。
	if _, err = sess.InsertOne(user); err != nil {
		// 发生错误时进行回滚
		_ = sess.Rollback()
		return -1,err
	}
	for _,v:=range userInfos{
		v.UserID=user.ID;
		if _, err = sess.InsertOne(v); err != nil {
			// 发生错误时进行回滚
			_ = sess.Rollback()
			return -1,err
		}
	}

	return user.ID,sess.Commit()
}
//

//CheckPasswd 校验密码
func (db *DB) CheckPasswd(user models.User) (bool, error) {
	count, err := db.Count(user)
	return count > 0, err
}
func (db *DB) DeleteUser(id int64) (count int64, err error) {
	count, err = db.ID(id).Delete(&models.User{})
	return
}

func (db *DB) PutUser(user models.User) (int64, error){
	count, err := db.Insert(user)
	return count, err
}
func (db *DB) UpdateUser(id int64,user models.User) (int64, error) {
	count, err := db.ID(id).Update(user)
	return count, err
}
//GetUserByID 根据用户ID获取用户
func (db *DB) GetUserByID(userID int64) (user models.User,find bool,err error) {
	find,err =db.Id(userID).Get(&user)
	return
}

//AllUsers 获取全部用户
func (db *DB) GetAllUsers(limit int, start ...int) (users []models.User,count int64, err error) {
	count,err=db.Count(&models.User{})
	err = db.Limit(limit, start...).Find(&users)
	return
}


//GetUserInfo 根据用户id获取用户全部信息
func (db *DB) GetUserInfo(userID int64, limit int, start... int) ([]models.UserInfo,  error) {
	//engine.Sql("select user.*, group.name from user, group where user.group_id = group.id").Find(&users)
	userInfo:= make([]models.UserInfo, 0)
	err := db.Where("user_id=?", userID).Limit(limit, start...).Find(userInfo)
	return userInfo,err;
}

func (db *DB) GetDBName() string  {
	return dbName;
}

func newDB(driverName, dataSourceName string) (models.DataAccessObject, error) {
	db, err := xorm.NewEngine(driverName, dataSourceName)
	if err != nil {
		return nil, err
	}
	if err = db.Ping(); err != nil {
		return nil, err
	}
	db.ShowSQL(true)
	db.ShowExecTime(true)
	db.SetLogLevel(0)
	db.Sync2(new(models.UserInfo), new(models.User))
	//db.Sync2()
	return &DB{db}, nil
}

func init() {
	fmt.Println("Mysql DataBase Init")
	db,_ :=newDB(dbName, "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")
	models.RegisterAdapter(db)
}
